package com.ruoyi.task.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.task.domain.ApiBean;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import static cn.hutool.core.lang.Console.log;


@Service
public class ApiService {
    public Map search(String link) {
        String newUrl = HttpUtil.get(link).split("\\?")[0].replace("<a href=\"", "");
        final String url = newUrl.split("/")[5];
        Map map = summer(url);
        final String msg = HttpUtil.get("https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=" + url);
        JSONObject arr = JSONObject.parseObject(msg);
        try {
            JSONObject obj = JSONObject.parseObject(arr.getJSONArray("item_list").get(0).toString());
            JSONObject data = obj.getJSONObject("statistics");
            Long diggCount = data.getLong("digg_count");
            Long commentCount = data.getLong("comment_count");
            map.put("视频点赞量",diggCount);
            map.put("评论量",commentCount);
            log("视频点赞量：" + diggCount + "\n评论量：" + commentCount);
        } catch (IndexOutOfBoundsException e) {
            map.put("msg","此为用户主页链接并非视频信息链接");
        }
        return map;
    }


    public static Map summer(String uid) {
        String newUrl = "https://www.iesdouyin.com/share/user/" + uid + "?sec_uid=MS4wLjABAAAACbVwXs-lhP-uufU7VeUVL7ialCrolMnrg2ZRd6khie0";
        String url = newUrl.split("\\?")[1];
        //https://www.iesdouyin.com/share/user/69656281696?sec_uid=MS4wLjABAAAACbVwXs-lhP-uufU7VeUVL7ialCrolMnrg2ZRd6khie0&amp;timestamp=1603802105&amp;utm_source=copy&amp;utm_campaign=client_share&amp;utm_medium=android&amp;share_app_name=douyin
        String param = HttpUtil.get("https://www.iesdouyin.com/web/api/v2/user/info/?" + url.replace("amp;", ""));
        JSONObject arr = JSONObject.parseObject(param);
        JSONObject userInfo = (JSONObject) arr.get("user_info");
        Long totalFavorited = userInfo.getLong("total_favorited");
        Long followingCount = userInfo.getLong("following_count");
        Long followerCount = userInfo.getLong("follower_count");
        Map<String,Long> map = new HashMap<>();
        map.put("关注量",followingCount);
        map.put("粉丝量",followerCount);
        map.put("总点赞量",totalFavorited);
        log("总点赞量：" + totalFavorited + "\n关注量：" + followingCount + "\n粉丝量：" + followerCount);
        return map;
    }
}
